import 'package:flutter/material.dart';
import 'package:x3_base_core/x3_base_core.dart';
import 'package:x3_form_core/x3_form_core.dart';
import 'package:x3_component_core/x3_component_core.dart';

class BaseRequestFormScanInputText extends StatefulWidget {
  final BaseHttpRequestModel request;
  final RequestSaveData requestSaveData;

  const BaseRequestFormScanInputText({Key key, @required this.request, this.requestSaveData}) : super(key: key);

  @override
  State<BaseRequestFormScanInputText> createState() => _BaseRequestFormScanInputTextState();
}

class _BaseRequestFormScanInputTextState extends State<BaseRequestFormScanInputText> {
  BaseRequestFormProvider _baseRequestFormProvider;

  /// 通过焦点消失回调
  FocusNode focusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    focusNode.addListener(() {
      if (!focusNode.hasFocus && widget.requestSaveData != null) {
        widget.requestSaveData(widget.request, _baseRequestFormProvider.getMapDataSource(widget.request), notShowLoading: true);
        //收回键盘
        FocusScope.of(context).requestFocus(FocusNode());
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    if (_baseRequestFormProvider == null) _baseRequestFormProvider = BaseRequestFormProvider.of(context);
    return BaseRequestFormContainer(
      request: widget.request,
      child: Row(
        children: [
          Expanded(child: buildTextField()),
          Container(margin: EdgeInsets.only(left: 6), child: _buildScanWidget()),
        ],
      ),
    );
  }

  Widget buildTextField() {
    var value = _baseRequestFormProvider.getDataSource(widget.request) ?? '';
    return BaseTextField(
      focusNode: focusNode,
      value: (value is String) == true ? value : value.toString(),
      readOnly: _baseRequestFormProvider.isReadonly(widget.request),
      hintText: widget.request.notes ?? "",
      emitFocusNode: _focusNodeListener,
      onSubmitted: (String value) {
        if (value.isEmpty && widget.request.required) {
          BaseUtils.showToast("${widget.request.name}不能为空");
          return;
        }
        _baseRequestFormProvider.setDataSource(widget.request, value);
        widget.requestSaveData(widget.request, _baseRequestFormProvider.getMapDataSource(widget.request));
      },
      onChanged: (String value) {
        /// 保存值
        _baseRequestFormProvider.setDataSource(widget.request, value);
      },
    );
  }

  /// 扫描组件
  Widget _buildScanWidget() {
    return Container(child: BaseScan(callBack: _onScan, customPress: null));
  }

  void _onScan(dynamic text) async {
    _baseRequestFormProvider.setDataSource(widget.request, text);
    setState(() {});
  }

  /// 监听焦点
  void _focusNodeListener(FocusNode focusNode) {
    focusNode.addListener(() {
      _baseRequestFormProvider.emitFocusNode(focusNode.hasFocus, widget.request);
    });
  }
}
